<!-- 登录界面 -->
<template>
  <div class="body">
    <div class="container">
      <h1 class="title">珞珈·音乐</h1>
      <p>欢迎您的到来</p>
    </div>

    <div class="container second">
      <div class="item">
        <div class="image img-first"></div>
        <div class="card">
          <h3>音乐推荐精选</h3>
          <p>
            畅游音乐海洋，发现独特旋律。精心挑选的音乐推荐，汇聚全球最新最热作品。独特标签、专业推荐算法，个性化音乐体验。加入我们，开始音乐探索！
          </p>
        </div>
      </div>
      <div class="item">
        <div class="image img-second"></div>
        <div class="card">
          <h3>音乐社区</h3>
          <p>
            汇聚音乐热情，分享创造力。展示才华，结识音乐爱好者。发表博客，互动交流。订阅创作者，获取最新作品。加入我们，融入音乐社区！
          </p>
        </div>
      </div>
      <div class="item">
        <div class="image img-third"></div>
        <div class="card">
          <h3>个性化歌单定制</h3>
          <p>
            专属私人DJ，调节心情。个性化歌单定制，根据喜好推荐音乐。悠扬旋律、爆棚曲风，贴合心情。加入我们，开启音乐对话！
          </p>
        </div>
      </div>
    </div>

    <div class="sign-section" id="sign-section">
      <div class="cont">
        <!-- 登录 -->

        <el-form
          v-if="!isForget"
          ref="signInForm"
          status-icon
          :model="loginForm"
          :rules="SignInRules"
          class="form sign-in"
        >
          <h2 class="sign-in-header">欢迎回珈</h2>
          <el-form-item prop="username" class="paperview-input-text username">
            <el-input
              placeholder="用户名"
              v-model="loginForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" class="paperview-input-text password">
            <el-input
              type="password"
              placeholder="密码"
              v-model="loginForm.password"
              @keyup.enter="handleLoginIn"
            ></el-input>
          </el-form-item>
          <p class="forgot-pass" @click="toggleForget">忘记密码?</p>

          <Vcode :show="isShow" @success="success" @close="close" @fail="fail">
          </Vcode>
          <button type="button" class="submit" @click="handleLoginIn">
            登录
          </button>
        </el-form>

        <!-- 忘记密码 -->
        <el-form
          v-show="isForget"
          ref="forgetForm"
          status-icon
          :model="forForm"
          :rules="SignInRules"
          class="form sign-in"
        >
          <h2 class="sign-in-header">找回密码</h2>
          <el-form-item prop="username" class="paperview-input-text username">
            <el-input placeholder="邮箱" v-model="forForm.email"></el-input>
          </el-form-item>
          <el-form-item prop="username" class="paperview-input-text username">
            <el-input
              placeholder="新密码"
              v-model="forForm.password"
            ></el-input>
          </el-form-item>
          <el-form-item prop="username" class="paperview-input-text username">
            <el-input
              placeholder="确认密码"
              v-model="forForm.cpassword"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="password"
            class="paperview-input-text password"
            id="bar"
          >
            <el-row justify="center" align="middle">
              <el-col :span="8">
                <el-input
                  type="password"
                  placeholder="验证码"
                  v-model="forForm.ma"
                  @keyup.enter="handleLoginIn"
                ></el-input>
              </el-col>
              <el-col :span="8"
                ><button id="button">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 24 24"
                    width="24"
                    height="24"
                  >
                    <path fill="none" d="M0 0h24v24H0z"></path>
                    <path
                      fill="currentColor"
                      d="M5 13c0-5.088 2.903-9.436 7-11.182C16.097 3.564 19 7.912 19 13c0 .823-.076 1.626-.22 2.403l1.94 1.832a.5.5 0 0 1 .095.603l-2.495 4.575a.5.5 0 0 1-.793.114l-2.234-2.234a1 1 0 0 0-.707-.293H9.414a1 1 0 0 0-.707.293l-2.234 2.234a.5.5 0 0 1-.793-.114l-2.495-4.575a.5.5 0 0 1 .095-.603l1.94-1.832C5.077 14.626 5 13.823 5 13zm1.476 6.696l.817-.817A3 3 0 0 1 9.414 18h5.172a3 3 0 0 1 2.121.879l.817.817.982-1.8-1.1-1.04a2 2 0 0 1-.593-1.82c.124-.664.187-1.345.187-2.036 0-3.87-1.995-7.3-5-8.96C8.995 5.7 7 9.13 7 13c0 .691.063 1.372.187 2.037a2 2 0 0 1-.593 1.82l-1.1 1.039.982 1.8zM12 13a2 2 0 1 1 0-4 2 2 0 0 1 0 4z"
                    ></path>
                  </svg>
                  <span>快速找回</span>
                </button></el-col
              >
            </el-row>
          </el-form-item>
          <p class="forgot-pass" @click="toggleForget">返回登录</p>

          <button type="button" class="submit" @click="handleLoginIn">
            找回密码
          </button>
        </el-form>

        <!-- 转换框 -->
        <div class="sub-cont">
          <div class="img">
            <div class="img__text m--up">
              <h2>没有账号？</h2>
              <p>注册账号，改善你的音乐体验！</p>
            </div>
            <div class="img__text m--in">
              <h2>已有账号？</h2>
              <p>重返珞珈社区</p>
            </div>
            <div class="img__btn">
              <span class="m--up">注册</span>
              <span class="m--in">登录</span>
            </div>
          </div>

          <!-- 注册 -->
          <div class="form sign-up">
            <h2>珈的感觉</h2>
            <el-form
              ref="signUpForm"
              label-width="70px"
              status-icon
              :model="registerForm"
              :rules="SignUpRules"
            >
              <el-form-item prop="username" label="用户名">
                <el-input
                  v-model="registerForm.username"
                  placeholder="用户名"
                ></el-input>
              </el-form-item>
              <el-form-item prop="password" label="密码">
                <el-input
                  type="password"
                  placeholder="密码"
                  v-model="registerForm.password"
                ></el-input>
              </el-form-item>
              <el-form-item prop="sex" label="性别">
                <el-radio-group v-model="registerForm.sex" class="radio-group">
                  <el-radio-button :label="0">女</el-radio-button>
                  <el-radio-button :label="1">男</el-radio-button>
                  <el-radio-button :label="2">保密</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="phoneNum" label="手机">
                <el-input
                  placeholder="手机"
                  v-model="registerForm.phoneNum"
                ></el-input>
              </el-form-item>
              <el-form-item prop="email" label="邮箱">
                <el-input
                  v-model="registerForm.email"
                  placeholder="邮箱"
                ></el-input>
              </el-form-item>
              <el-form-item prop="birth" label="生日">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="registerForm.birth"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
              <el-form-item prop="introduction" label="签名">
                <el-input
                  type="textarea"
                  placeholder="签名"
                  v-model="registerForm.introduction"
                ></el-input>
              </el-form-item>
              <el-form-item prop="location" label="地区">
                <el-select
                  v-model="registerForm.location"
                  placeholder="地区"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in AREA"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <button type="button" class="submit" @click="handleSignUp()">
                注册
              </button>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  getCurrentInstance,
  ref,
  onMounted,
} from "vue";
import mixin from "@/mixins/mixin";
import { HttpManager } from "@/api";
import { NavName, RouterName, SignInRules } from "@/enums";
import { getBirth } from "@/utils";
import { AREA, SignUpRules } from "@/enums";
import Vcode from "vue3-puzzle-vcode";
import axios from "axios";

export default defineComponent({
  components: {
    Vcode,
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const { routerManager, changeIndex } = mixin();
    const userList = ref([]); //用户创建的歌单列表
    // 用户名，密码
    const loginForm = reactive({
      username: "",
      password: "",
    });
    const isShow = ref(false);
    const isSuccess = ref(false);
    const isForget = ref(false);

    const forForm = reactive({
      email: "",
      password: "",
      cpassword: "",
      ma: "",
    });

    // 定义方法

    function toggleForget() {
      isForget.value = !isForget.value;
    }
    function submit() {
      isShow.value = true;
    }

    function success(msg) {
      isShow.value = false;
      console.log("验证通过" + msg);
    }

    function close() {
      isShow.value = false;
    }

    function fail() {
      console.log("验证失败");
    }

    //获取用户歌单
    async function getUSongList(value) {
      if (!value) return;
      const result = (await HttpManager.getUserSongList(value)) as ResponseBody;
      userList.value = result.data;
      let results = [];
      for (let i = 0; i < userList.value.length; i++) {
        results.push({
          label: userList.value[i].title,
          value: userList.value[i].id,
        });
      }
      proxy.$store.commit("setUserSongList", results);
    }

    //处理登录
    async function handleLoginIn() {
      let canRun = true;
      (proxy.$refs["signInForm"] as any).validate((valid) => {
        if (!valid) return (canRun = false);
      });
      if (!canRun) return;

      const params = new URLSearchParams();
      params.append("username", loginForm.username);
      params.append("password", loginForm.password);

      isShow.value = true;
      if (isShow.value) {
        await new Promise((resolve) => {
          const intervalId = setInterval(() => {
            if (!isShow.value) {
              clearInterval(intervalId);
              resolve(1);
            }
          }, 100); // 每100毫秒检查一次isShow.value的值
        });
      }

      try {
        //发送账号和密码，请求结果
        const result = (await HttpManager.signIn(params)) as ResponseBody;
        (proxy as any).$message({
          message: result.message,
          type: result.type,
        });
        // 将登录用户的信息存储在store
        if (result.success) {
          proxy.$store.commit("setUserId", result.data.user.id);
          proxy.$store.commit("setUsername", result.data.user.username);
          proxy.$store.commit("setUserPic", result.data.user.avator);
          proxy.$store.commit("setToken", true);
          proxy.$store.commit("setIsVisitor", true);
          console.log(result.data.token);
          axios.defaults.headers.common["token"] = result.data.token;
          getUSongList(proxy.$store.getters.userId);
          changeIndex(NavName.Home);
          routerManager(RouterName.Home, { path: RouterName.Home });
        }
      } catch (error) {
        console.error(error);
      }
    }

    const registerForm = reactive({
      username: "",
      password: "",
      sex: "",
      phoneNum: "",
      email: "",
      birth: new Date(),
      introduction: "",
      location: "",
    });

    async function handleSignUp() {
      let canRun = true;
      (proxy.$refs["signUpForm"] as any).validate((valid) => {
        if (!valid) return (canRun = false);
      });
      if (!canRun) return;

      const params = new URLSearchParams();
      params.append("username", registerForm.username);
      params.append("password", registerForm.password);
      params.append("sex", registerForm.sex);
      params.append("phone_num", registerForm.phoneNum);
      params.append("email", registerForm.email);
      params.append("birth", getBirth(registerForm.birth));
      params.append("introduction", registerForm.introduction);
      params.append("location", registerForm.location);

      try {
        const result = (await HttpManager.SignUp(params)) as ResponseBody;
        (proxy as any).$message({
          message: result.message,
          type: result.type,
        });

        if (result.success) {
          changeIndex(NavName.SignIn);
          routerManager(RouterName.SignIn, { path: RouterName.SignIn });
        }
      } catch (error) {
        console.error(error);
      }
    }

    //渲染函数
    onMounted(() => {
      document
        .querySelector(".img__btn")
        .addEventListener("click", function () {
          document.querySelector(".cont").classList.toggle("s--signup");
        });
    });

    function scrollDown() {
      console.log(999);
      window.scrollTo({
        top: document.documentElement.offsetHeight, //回到底部
        left: 0,
        behavior: "smooth", //smooth 平滑；auto:瞬间
      });
    }

    return {
      forForm,
      registerForm,
      loginForm,
      SignInRules,
      SignUpRules,
      AREA,
      handleLoginIn,
      handleSignUp,
      getUSongList,
      isShow,
      submit,
      success,
      close,
      fail,
      isForget,
      isSuccess: false,
      toggleForget,
      scrollDown,
    };
  },
});
</script>

<style lang="scss" scoped>
@import ".././assets/css/sign.scss";
@import url("https://fonts.googleapis.com/css2?family=Ma+Shan+Zheng&display=swap");

.el-form-item {
  margin-top: 3px;
}
.sign-in {
  margin-top: 50px;
}
#bar {
  display: flex;
}
#button {
  margin-left: 10px;
  width: 140px;
  display: flex;
  align-items: center;
  font-family: inherit;
  font-weight: 500;
  font-size: 17px;
  padding: 0.8em 1.3em 0.8em 0.9em;
  color: white;
  background: #ad5389;
  background: linear-gradient(to right, #0f0c29, #302b63, #24243e);
  border: none;
  letter-spacing: 0.05em;
  border-radius: 16px;
}

#button svg {
  margin-right: 3px;
  transform: rotate(30deg);
  transition: transform 0.5s cubic-bezier(0.76, 0, 0.24, 1);
}

#button span {
  transition: transform 0.5s cubic-bezier(0.76, 0, 0.24, 1);
}

#button:hover svg {
  transform: translateX(5px) rotate(90deg);
}

#button:hover span {
  transform: translateX(7px);
}

.item {
  height: 450px;
}
.title {
  font-size: 80px;
  font-family: "Ma Shan Zheng", cursive;
}
</style>
